import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// import viteCompression from 'vite-plugin-compression'//gzip压缩
// import viteImagemin from 'vite-plugin-imagemin'//图片压缩
import { visualizer } from "rollup-plugin-visualizer";//分析打包体积
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createHtmlPlugin } from 'vite-plugin-html'
import externalGlobals from "rollup-plugin-external-globals";
// 而使用 rollup-plugin-external-globals 插件，则能够告诉 Rollup，将 $ 变量绑定到模块的导出上，避免抛出错误。

// 生产环境
const isProduction = process.env.NODE_ENV === "production";

const plugins = []
let build = {}
const scriptConfig = {
  vueScript: '',
  demiScript: '',
  routerScript: '',
}
if (isProduction) {
  plugins.push(
    visualizer({
      emitFile: true, // 打包后的分析文件会出现在打包好的文件包下
      filename: 'state.html', // 分析图生成的文件名
      open: true // 如果存在本地服务端口，将在打包后自动展示
      // sourcemap: true// 使用sourcemap计算大小
    })
  )
  scriptConfig.vueScript = '<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.3.4/vue.global.prod.min.js"></script>'
  scriptConfig.demiScript = '<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-demi/0.14.6/index.iife.min.js"></script>'
  scriptConfig.routerScript = '<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/4.2.4/vue-router.global.prod.min.js"></script>'
  build = {
    terserOptions: {
      compress: {
        drop_console: true, // 去除console.log等语句
        drop_debugger: true, // 去除debugger语句
      },
    },
    rollupOptions: {
      // 不打包依赖
      external: ['vue', 'vue-router'],
      plugins: [
        // 不打包依赖映射的对象
        externalGlobals({
          // "在项目中引入的变量名称"："CDN包导出的名称，一般在CDN包中都是可见的"
          vue: 'Vue',
          'vue-demi': 'VueDemi',
          'vue-router': 'vue-router'
          // '$': 'jquery',
          // '_': 'lodash',
        })
      ]
    }
  }
}

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
    createHtmlPlugin({
      minify: true,
      inject: {
        data: scriptConfig
      }
    }),
    ...plugins
  ],
  build,
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server: {
    open: true,
    host: '0.0.0.0',
    port: 3000,
    proxy: {
      '/api': {
        target: 'http://localhost:9999',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    }
  }
})
